// ignore_for_file: file_names, must_be_immutable, constant_identifier_names, slash_for_doc_comments, avoid_unnecessary_containers, prefer_const_constructors, unnecessary_cast, sized_box_for_whitespace, prefer_function_declarations_over_variables, overridden_fields, annotate_overrides, prefer_const_literals_to_create_immutables, unnecessary_null_comparison, deprecated_member_use

import 'package:flutter/material.dart';
import 'package:mybase/base/tool/color/FFColor.dart';
import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:mybase/base/tool/extension/FFColorExt.dart';
import 'package:mybase/base/tool/sputils/FFSpUtils.dart';

// 主题管理
class FFThemeManager {
  // 单例公开访问点
  factory FFThemeManager() => _sharedInstance();

  // 静态、同步、私有访问点
  static FFThemeManager _sharedInstance() {
    return _instance;
  }

  // 静态私有成员，没有初始化
  static final FFThemeManager _instance = FFThemeManager._();

  late ThemeData themeData;
  ThemeManagerDelegate? delegate;
  final String spPrimaryColor = "FFThemeManager.spPrimaryColor";

  // 私有构造函数
  FFThemeManager._() {}

  /**
   * @title 初始化主题
   * @info  如果已经有主题色，则使用上次的主题色
   */
  Future<void> initTheme({
    Color? primaryColor = Colors.red,
  }) async {
    String? colorStr = await FFSpUtils.getData(spPrimaryColor);

    Color? color = primaryColor;
    if (!FFEmpty.stringIsEmpty(colorStr)) {
      color = hex(colorStr!);
    }

    themeData = ThemeData(
      primarySwatch: color!.toMaterialColor,
      primaryColor: color.toMaterialColor,
      splashColor: color,
      highlightColor: color,
      platform: TargetPlatform.iOS,
    );
  }

  /**
   * @title 主题颜色切换
   */
  Future<void> changeTheme(Color primaryColor) async {
    themeData = ThemeData(
      primarySwatch: primaryColor.toMaterialColor,
      primaryColor: primaryColor.toMaterialColor,
      platform: TargetPlatform.iOS,
    );
    delegate?.onThemeChange(themeData);

    // 把用到的颜色 保存一下
    await FFSpUtils.saveData(
        spPrimaryColor, primaryColor.value.toRadixString(16));
  }

  /**
   * @title 更新自定义主题
   * @info  customThemeDatas需要执行一次copyWith才会生效
   */
  changeCustomTheme(dynamic customThemeData) {
    delegate?.onCustomThemeChange(customThemeData);
  }
}

abstract class ThemeManagerDelegate {
  /**
   * @title 系统主题改变时
   */
  void onThemeChange(ThemeData themeData) {}

  /**
   * @title 自定义主题改变时
   */
  void onCustomThemeChange(dynamic customThemeData) {}
}
